<template>
  <div class="app-container">
    <!-- 工单信息卡片 - 固定在顶部 -->
    <el-card class="box-card info-card">
      <div slot="header" class="clearfix">
        <span>工单信息</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="goBack">返回</el-button>
      </div>
      <el-form label-position="left" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="工单编号">
              <span>{{ workOrderInfo.workOrderCode }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="工单名称">
              <span>{{ workOrderInfo.workOrderName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="关联计划">
              <span>{{ workOrderInfo.planName }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="产品名称">
              <span>{{ workOrderInfo.productName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="产品编号">
              <span>{{ workOrderInfo.productCode }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="规格型号">
              <span>{{ workOrderInfo.specification }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="计划数量">
              <span>{{ workOrderInfo.plannedQty }}</span>
              <el-tooltip content="工序任务数量可以超出工单计划数量，以适应多做工序的需求" placement="top">
                <i class="el-icon-info" style="margin-left: 5px; color: #909399; cursor: pointer;"></i>
              </el-tooltip>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单位">
              <span>{{ workOrderInfo.unit }}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 可滚动的内容区域 -->
    <div class="scrollable-content">
      <!-- 工序任务分配卡片 -->
      <el-card class="box-card task-card">
        <div slot="header" class="clearfix">
          <span>工序任务分配</span>
          <el-button style="float: right;" type="primary" size="mini" @click="addTask">添加临时工序</el-button>
        </div>
        <div class="task-table-container">
          <el-alert
            title="提示：标准工艺路线中的工序不可删除，只能调整工位和时间。可以添加临时工序（如返工、维修等）进行排产。"
            type="info"
            :closable="false"
            show-icon
            style="margin-bottom: 10px;"
          />
          <el-table v-loading="loading" :data="taskList" style="width: 100%" height="300">
            <el-table-column label="序号" type="index" width="55" align="center" />
            <el-table-column label="工序" align="center" width="200">
              <template slot-scope="scope">
                <!-- 如果已有工序ID且有工序名称，直接显示工序名称 -->
                <div v-if="scope.row.processId && scope.row.processName && !scope.row.editingProcess" class="process-display">
                  <span>{{ scope.row.processName }}</span>
                  <el-button
                    type="text"
                    size="mini"
                    icon="el-icon-edit"
                    @click="editProcess(scope.$index)"
                    style="margin-left: 8px;"
                  ></el-button>
                </div>
                <!-- 未分配工序或编辑状态时显示选择框 -->
                <div v-else class="process-select">
                  <el-select
                    v-model="scope.row.processId"
                    placeholder="请选择工序"
                    @change="handleProcessChange(scope.$index, scope.row)"
                    size="mini"
                  >
                    <el-option
                      v-for="item in processList"
                      :key="item.processId"
                      :label="item.processName"
                      :value="item.processId"
                    ></el-option>
                  </el-select>
                  <el-button
                    v-if="scope.row.editingProcess"
                    type="text"
                    size="mini"
                    icon="el-icon-check"
                    @click="confirmProcessSelection(scope.$index)"
                    style="margin-left: 4px;"
                  ></el-button>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="工位" align="center" width="200">
              <template slot-scope="scope">
                <!-- 始终显示工位选择框，如果有stationId则默认选中 -->
                <div class="station-select">
                  <el-select
                    v-model="scope.row.stationId"
                    placeholder="请选择工位"
                    @change="onStationChange(scope.$index, $event)"
                    size="mini"
                  >
                    <el-option
                      v-for="item in getAvailableStations(scope.row.processId)"
                      :key="item.stationId"
                      :label="item.stationName"
                      :value="item.stationId"
                    ></el-option>
                  </el-select>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="计划数量" align="center" width="180">
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.qtyNum"
                  :min="1"
                  size="mini"
                  @change="handleQtyChange(scope.row, scope.$index)"
                ></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="开始时间" align="center" width="220">
              <template slot-scope="scope">
                <el-date-picker
                  v-model="scope.row.startTime"
                  type="datetime"
                  placeholder="选择日期时间"
                  size="mini"
                  value-format="yyyy-MM-dd HH:mm:ss"
                ></el-date-picker>
              </template>
            </el-table-column>
            <el-table-column label="结束时间" align="center" width="220">
              <template slot-scope="scope">
                <el-date-picker
                  v-model="scope.row.endTime"
                  type="datetime"
                  placeholder="选择日期时间"
                  size="mini"
                  value-format="yyyy-MM-dd HH:mm:ss"
                ></el-date-picker>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="danger"
                  @click="removeTask(scope.$index)"
                  v-if="!isStandardProcess(scope.row.processId)"
                >删除</el-button>
                <span v-else>标准工序</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div style="margin-top: 20px; text-align: center;">
          <el-button type="primary" @click="submitSchedule">提交排产</el-button>
          <el-button @click="goBack">取消</el-button>
        </div>
      </el-card>

      <!-- 甘特图卡片 -->
      <el-card class="box-card gantt-card">
        <div slot="header" class="clearfix">
          <span>排产甘特图</span>
        </div>
        <!-- ECharts 甘特图容器 -->
        <div id="gantt-chart" style="width: 100%; height: 350px;"></div>
      </el-card>
    </div>
  </div>
</template>

<script>
import { getWorkOrder, scheduleWorkOrder } from "@/api/sc/workOrder";
import * as echarts from 'echarts';

export default {
  name: "WorkOrderScheduling",
  data() {
    return {
      // 工单ID
      workOrderId: undefined,
      // 工单编号
      workOrderCode: undefined,
      // 工单信息
      workOrderInfo: {},
      // 工序任务列表
      taskList: [],
      // 工序列表
      processList: [],
      // 工位列表
      stationList: [],
      // 加载状态
      loading: false,
      // ECharts 实例
      ganttChart: null
    };
  },
  watch: {
    '$route'(to, from) {
      if (to.query.workOrderId && to.query.workOrderId !== from.query.workOrderId) {
        this.workOrderId = to.query.workOrderId;
        this.workOrderCode = to.query.workOrderCode;
        console.log('工单排产页面路由变化，刷新数据');
        this.getWorkOrderInfo();
      }
    },
    // 监听工单ID变化
    workOrderId(newVal, oldVal) {
      if (newVal && newVal !== oldVal) {
        console.log('工单ID变化，刷新排产数据');
        this.getWorkOrderInfo();
      }
    },
    taskList: {
      handler(newTasks) {
        this.$nextTick(() => {
          this.initGanttChart(newTasks);
        });
      },
      deep: true
    }
  },
  mounted() {
    this.initGanttChart(this.taskList);
  },
  activated() {
    // 兼容 keep-alive
    if (this.ganttChart) {
      this.ganttChart.resize();
    }
  },
  beforeDestroy() {
    if (this.ganttChart) {
      this.ganttChart.dispose();
      this.ganttChart = null;
    }
  },
  created() {
    this.workOrderId = this.$route.query.workOrderId;
    this.workOrderCode = this.$route.query.workOrderCode;
    this.getWorkOrderInfo();
  },
  methods: {
    // 初始化 ECharts 甘特图
    initGanttChart(tasks) {
      if (!tasks || tasks.length === 0) return;

      // 确保 DOM 元素存在
      const chartDom = document.getElementById('gantt-chart');
      if (!chartDom) return;

      // 如果 ECharts 实例不存在则初始化，否则使用已有的实例
      if (!this.ganttChart) {
        this.ganttChart = echarts.init(chartDom);
      }
      
      // 保存this引用
      const self = this;
      
      // 收集工序名称作为Y轴数据
      const processNames = tasks.map(task => this.getProcessName(task.processId));
      
      // 使用统一的日期处理函数
      function parseDateTime(dateTimeStr) {
        if (!dateTimeStr) return null;
        
        // 处理字符串格式的日期时间 "yyyy-MM-dd HH:mm:ss"
        const parts = dateTimeStr.split(' ');
        if (parts.length === 2) {
          const dateParts = parts[0].split('-');
          const timeParts = parts[1].split(':');
          
          if (dateParts.length === 3 && timeParts.length === 3) {
            const year = parseInt(dateParts[0]);
            const month = parseInt(dateParts[1]) - 1; // 月份是0-11
            const day = parseInt(dateParts[2]);
            const hour = parseInt(timeParts[0]);
            const minute = parseInt(timeParts[1]);
            const second = parseInt(timeParts[2]);
            
            const date = new Date(year, month, day, hour, minute, second);
            return date;
          }
        }
        
        // 如果特定格式解析失败，尝试默认解析
        const date = new Date(dateTimeStr);
        return date;
      }
      
      // 创建甘特图数据（简化版，直接使用普通bar图表实现）
      const seriesData = [];
      
      // 记录最早和最晚的时间，用于调试
      let earliestTime = Infinity;
      let latestTime = -Infinity;
      
      tasks.forEach((task, index) => {
        if (!task.startTime || !task.endTime) {
          console.warn(`任务${index} "${this.getProcessName(task.processId)}" 缺少开始或结束时间`);
          return;
        }
        
        const startDate = parseDateTime(task.startTime);
        const endDate = parseDateTime(task.endTime);
        
        if (!startDate || !endDate || isNaN(startDate.getTime()) || isNaN(endDate.getTime())) {
          console.warn(`任务${index} "${this.getProcessName(task.processId)}" 日期解析失败:`, 
            { start: task.startTime, end: task.endTime });
          return;
        }
        
        const startTime = startDate.getTime();
        const endTime = endDate.getTime();
        
        // 检查时间段是否有效
        if (startTime >= endTime) {
          console.warn(`任务${index} "${this.getProcessName(task.processId)}" 开始时间晚于或等于结束时间:`,
            { startTime, endTime, start: task.startTime, end: task.endTime });
          return;
        }
        
        // 更新时间范围
        if (startTime < earliestTime) earliestTime = startTime;
        if (endTime > latestTime) latestTime = endTime;
        
        // 记录任务数据
        seriesData.push({
          value: [startTime, endTime, index],
          itemStyle: {
            normal: {
              color: '#409eff'  // 使用Element UI主色
            }
          }
        });
      });
      
      // 创建简化的甘特图选项
      const option = {
        title: {
          text: '排产甘特图',
          left: 'left',
          top: 0,
          textStyle: {
            fontSize: 16,
            fontWeight: 'normal'
          }
        },
        tooltip: {
          formatter: function(params) {
            const task = tasks[params.value[2]];
            if (!task) return '';
            
            // 格式化日期: yyyy-MM-dd HH:mm
            const formatDateTime = (dateTimeStr) => {
              if (!dateTimeStr) return '';
              const date = new Date(dateTimeStr);
              return date.getFullYear() + '-' + 
                     String(date.getMonth()+1).padStart(2,'0') + '-' + 
                     String(date.getDate()).padStart(2,'0') + ' ' + 
                     String(date.getHours()).padStart(2,'0') + ':' + 
                     String(date.getMinutes()).padStart(2,'0');
            };
            
            const processName = self.getProcessName(task.processId);
            const stationName = self.getStationName(task.stationId) || '未分配';
            
            return `
              <div style="font-weight:bold; margin-bottom:5px; font-size:14px">${processName}</div>
              <div><b>工位:</b> ${stationName}</div>
              <div><b>开始:</b> ${formatDateTime(task.startTime)}</div>
              <div><b>结束:</b> ${formatDateTime(task.endTime)}</div>
              <div><b>数量:</b> ${task.qtyNum || 0}</div>
            `;
          },
          backgroundColor: 'rgba(50,50,50,0.8)',
          borderColor: '#333',
          borderWidth: 0,
          padding: 10,
          textStyle: {
            color: '#fff',
            fontSize: 13
          }
        },
        toolbox: {
          feature: {
            dataZoom: {
              yAxisIndex: 'none',
              title: {
                zoom: '区域缩放',
                back: '还原缩放'
              }
            },
            restore: {
              title: '重置'
            },
            saveAsImage: {
              title: '保存为图片'
            }
          },
          right: 20,
          top: 0
        },
        dataZoom: [
          {
            type: 'slider',
            xAxisIndex: 0,
            filterMode: 'weakFilter',
            height: 20,
            bottom: 10,
            start: 0,
            end: 100,
            handleStyle: {
              color: '#409eff',
              shadowBlur: 3,
              shadowColor: 'rgba(0,0,0,0.3)',
              shadowOffsetX: 2,
              shadowOffsetY: 2
            },
            textStyle: {
              color: '#999'
            }
          }
        ],
        grid: {
          height: 360,
          left: '5%',
          right: '4%', 
          bottom: 60,
          top: 50,
          containLabel: true
        },
        xAxis: {
          type: 'time',
          // 移除min和max设置，让ECharts自动计算
          axisLine: {
            lineStyle: {
              color: '#666'
            }
          },
          axisLabel: {
            formatter: function(value) {
              const date = new Date(value);
              return `${date.getFullYear()}/${(date.getMonth()+1).toString().padStart(2, '0')}/${date.getDate().toString().padStart(2, '0')}`;
            },
            interval: 0,
            rotate: 30,
            margin: 15,
            textStyle: {
              fontSize: 12
            }
          },
          splitLine: {
            show: true,
            lineStyle: {
              type: 'dashed',
              color: '#ddd'
            }
          },
          axisTick: {
            show: true,
            alignWithLabel: true,
            length: 5,
            lineStyle: {
              color: '#999'
            }
          },
          minInterval: 3600 * 24 * 1000 // 最小间隔为一天
        },
        yAxis: {
          type: 'category',
          data: processNames,
          axisLabel: {
            interval: 0,
            textStyle: {
              fontSize: 12,
              color: '#333'
            },
            formatter: function(value) {
              // 如果工序名称太长，截断并添加省略号
              if (value.length > 10) {
                return value.substring(0, 10) + '...';
              }
              return value;
            }
          },
          axisTick: {
            show: true,
            alignWithLabel: true,
            lineStyle: {
              color: '#999'
            }
          },
          axisLine: {
            lineStyle: {
              color: '#ddd'
            }
          },
          splitLine: {
            show: true,
            lineStyle: {
              color: '#f5f5f5'
            }
          }
        },
        series: [{
          type: 'custom',
          renderItem: function(params, api) {
            const index = api.value(2);
            const start = api.coord([api.value(0), index]);
            const end = api.coord([api.value(1), index]);
            const height = api.size([0, 1])[1] * 0.7;  // 增加高度到70%
            
            const width = Math.max(end[0] - start[0], 3);
            
            return {
              type: 'group',
              children: [
                {
                  // 阴影效果
                  type: 'rect',
                  shape: {
                    x: start[0] + 1,
                    y: start[1] - height / 2 + 2,
                    width: width,
                    height: height,
                    r: 4  // 圆角
                  },
                  style: {
                    fill: 'rgba(0,0,0,0.2)'
                  }
                },
                {
                  // 主要条形
                  type: 'rect',
                  shape: {
                    x: start[0],
                    y: start[1] - height / 2,
                    width: width,
                    height: height,
                    r: 4  // 圆角
                  },
                  style: {
                    fill: api.visual('color'),
                    stroke: 'rgba(255,255,255,0.3)',
                    lineWidth: 1
                  }
                }
              ]
            };
          },
          itemStyle: {
            color: function(params) {
              // 渐变色数组，丰富视觉效果
              const colors = [
                {
                  type: 'linear',
                  x: 0, y: 0, x2: 1, y2: 0,
                  colorStops: [
                    {offset: 0, color: '#1890ff'}, 
                    {offset: 1, color: '#73c9ff'}
                  ]
                },
                {
                  type: 'linear',
                  x: 0, y: 0, x2: 1, y2: 0,
                  colorStops: [
                    {offset: 0, color: '#36cfc9'}, 
                    {offset: 1, color: '#70e0df'}
                  ]
                },
                {
                  type: 'linear',
                  x: 0, y: 0, x2: 1, y2: 0,
                  colorStops: [
                    {offset: 0, color: '#ff7a45'}, 
                    {offset: 1, color: '#ffa981'}
                  ]
                },
                {
                  type: 'linear',
                  x: 0, y: 0, x2: 1, y2: 0,
                  colorStops: [
                    {offset: 0, color: '#722ed1'}, 
                    {offset: 1, color: '#9254de'}
                  ]
                },
                {
                  type: 'linear',
                  x: 0, y: 0, x2: 1, y2: 0,
                  colorStops: [
                    {offset: 0, color: '#52c41a'}, 
                    {offset: 1, color: '#85ed54'}
                  ]
                }
              ];
              return colors[params.dataIndex % colors.length];
            },
            shadowBlur: 4,
            shadowColor: 'rgba(0,0,0,0.2)',
            shadowOffsetX: 0,
            shadowOffsetY: 2,
            borderRadius: 4
          },
          encode: {
            x: [0, 1],
            y: 2
          },
          data: seriesData,
          z: 2
        }]
      };
      
      // 设置图表
      this.ganttChart.setOption(option, true);  // true表示不合并之前的选项，完全替换
      
      // 监听窗口大小变化
      window.addEventListener('resize', () => {
        if (this.ganttChart) {
          this.ganttChart.resize();
        }
      });
    },

    // 判断是否为标准工艺路线中的工序
    isStandardProcess(processId) {
      // 检查工序ID是否属于标准工艺路线（钢材MES系统中的标准工序）
      const standardProcessIds = [201, 202, 203];
      return standardProcessIds.includes(processId);
    },

    // 获取工单信息
    getWorkOrderInfo() {
      if (!this.workOrderId) return;
      this.loading = true;
      getWorkOrder(this.workOrderId).then(response => {
        const data = response.data;
        console.log('排产页面获取工单数据:', data);

        // 1. 设置工单信息
        this.workOrderInfo = data.workOrder || {};
        console.log('工单信息:', this.workOrderInfo);

        // 2. 转换工序和工位列表
        this.processList = (data.processList || []).map(p => ({
          processId: p.process_id,
          processName: p.process_name,
          processCode: p.process_code,
        }));
        
        this.stationList = (data.stationList || []).map(s => ({
          stationId: s.station_id,
          stationName: s.station_name,
          processId: s.process_id,
        }));
        console.log('工位列表:', this.stationList);
        
        // 3. 转换并丰富任务列表，确保每个任务都有 processName 和默认时间
        const tasks = data.taskList || [];
        console.log('原始任务列表:', tasks);

        // 设置基准日期为当前日期
        const baseDate = new Date();
        let lastEndDate = new Date(baseDate);

        tasks.forEach((task, index) => {
            // 字段映射：后端使用 plannedQty，前端使用 qtyNum
            if (task.plannedQty) {
              task.qtyNum = task.plannedQty;
            }
            // 如果后端没有返回计划数量，使用工单计划数量作为默认值
            else if (!task.qtyNum) {
              task.qtyNum = this.workOrderInfo.plannedQty || this.workOrderInfo.qtyNum || 1;
            }

            // 只在processName为空时才使用getProcessName方法，避免覆盖后端返回的正确数据
            if (!task.processName) {
              task.processName = this.getProcessName(task.processId);
            }

            // 自动分配默认工位：如果有工序但没有工位，选择该工序的第一个可用工位
            if (task.processId && !task.stationId) {
              const availableStations = this.stationList.filter(s => s.processId === task.processId);
              if (availableStations.length > 0) {
                task.stationId = availableStations[0].stationId;
                task.stationName = availableStations[0].stationName;
                console.log(`为工序 ${task.processName} 自动分配工位: ${task.stationName}`);
              }
            }

            // 为任务设置错开的默认时间
            if (!task.startTime || !task.endTime) {
              // 为第一个任务设置当天开始时间
              if (index === 0) {
                task.startTime = this.getFormattedDate(baseDate);

                // 设置持续时间为1-3天
                const duration = Math.floor(Math.random() * 3) + 1; // 1-3天
                const endDate = new Date(baseDate);
                endDate.setDate(endDate.getDate() + duration);
                task.endTime = this.getFormattedDate(endDate);

                // 更新最后结束日期
                lastEndDate = new Date(endDate);
              } else {
                // 为后续任务设置错开的时间（基于上一个任务的结束日期）
                // 随机间隔3-20天
                const interval = Math.floor(Math.random() * 18) + 3; // 3-20天
                const startDate = new Date(lastEndDate);
                startDate.setDate(startDate.getDate() + interval);
                task.startTime = this.getFormattedDate(startDate);

                // 设置持续时间为1-5天
                const duration = Math.floor(Math.random() * 5) + 1; // 1-5天
                const endDate = new Date(startDate);
                endDate.setDate(endDate.getDate() + duration);
                task.endTime = this.getFormattedDate(endDate);

                // 更新最后结束日期
                lastEndDate = new Date(endDate);
              }
            }
        });
        console.log('处理后任务列表:', tasks);
        this.taskList = tasks;

        this.loading = false;
      }).catch((error) => {
        this.loading = false;
        console.error("获取工单信息失败:", error);
        this.$modal.msgError("获取工单信息失败，请按F12查看控制台获取详细错误信息。");
      });
    },
    
    // 获取格式化的日期时间字符串
    getFormattedDate(date) {
      return date.getFullYear() + '-' + 
        String(date.getMonth()+1).padStart(2,'0') + '-' + 
        String(date.getDate()).padStart(2,'0') + ' ' + 
        String(date.getHours()).padStart(2,'0') + ':' + 
        String(date.getMinutes()).padStart(2,'0') + ':' + 
        String(date.getSeconds()).padStart(2,'0');
    },
    
    // 获取工序列表 - 在新逻辑下，此方法不再由 created 直接调用
    getProcessList() {
      // 模拟数据
      this.processList = [
        { processId: 1, processName: '备料工序' },
        { processId: 2, processName: '组装工序' },
        { processId: 3, processName: '检验工序' },
        { processId: 4, processName: '包装工序' }
      ];
    },
    
    // 获取工位列表 - 在新逻辑下，此方法不再由 created 直接调用
    getStationList() {
      // 模拟数据
      this.stationList = [
        { stationId: 1, stationName: '工位A' },
        { stationId: 2, stationName: '工位B' },
        { stationId: 3, stationName: '工位C' },
        { stationId: 4, stationName: '工位D' }
      ];
    },
    
    // 返回上级页面
    goBack() {
      this.$router.go(-1);
    },
    
    // 添加工序任务
    addTask() {
      // 只允许添加非标准工艺路线中的工序（如返工、维修等）
      
      // 计算新任务的开始日期（从最后一个任务的结束时间开始）
      let startDate;
      if (this.taskList.length > 0) {
        const lastTask = this.taskList[this.taskList.length - 1];
        if (lastTask.endTime) {
          startDate = new Date(lastTask.endTime);
          // 增加3-20天随机间隔
          const interval = Math.floor(Math.random() * 18) + 3; // 3-20天
          startDate.setDate(startDate.getDate() + interval);
        } else {
          startDate = new Date();
        }
      } else {
        startDate = new Date();
      }
      
      // 计算结束日期（开始日期 + 1-5天随机持续时间）
      const duration = Math.floor(Math.random() * 5) + 1; // 1-5天
      const endDate = new Date(startDate);
      endDate.setDate(endDate.getDate() + duration);
      
      const newTask = {
        workOrderTaskId: Date.now(), // 临时ID，仅用于前端key
        isNew: true, // 明确标记为新任务
        processId: undefined,
        stationId: undefined,
        qtyNum: this.workOrderInfo.plannedQty || this.workOrderInfo.qtyNum || 1,
        completedQty: 0,
        startTime: this.getFormattedDate(startDate),
        endTime: this.getFormattedDate(endDate)
      };
      this.taskList.push(newTask);
    },
    
    // 删除工序任务
    removeTask(index) {
      // 根据钢材行业MES标准，只允许删除非标准工艺路线中的工序
      const task = this.taskList[index];
      if (this.isStandardProcess(task.processId)) {
        this.$modal.msgWarning("标准工艺路线中的工序不允许删除");
        return;
      }
      this.taskList.splice(index, 1);
    },

    // 处理工序任务数量变化
    handleQtyChange(task, index) {
      if (!task.qtyNum || task.qtyNum <= 0) {
        task.qtyNum = 1;
        return;
      }
    },

    // 处理工序变更
    handleProcessChange(index, row) {
      // 当工序变更时，更新工序名称并清空工位选择
      if (row.processId) {
        row.processName = this.getProcessName(row.processId);
      }
      row.stationId = undefined;
    },

    // 编辑工序
    editProcess(index) {
      this.$set(this.taskList[index], 'editingProcess', true);
    },

    // 确认工序选择
    confirmProcessSelection(index) {
      const task = this.taskList[index];
      // 更新工序名称
      if (task.processId) {
        task.processName = this.getProcessName(task.processId);
      }
      this.$set(this.taskList[index], 'editingProcess', false);
    },

    // 获取工序名称
    getProcessName(processId) {
      if (!processId) return '未选择工序';
      const process = this.processList.find(p => p.processId === processId);
      const result = process ? process.processName : '未知工序';
      return result;
    },

    getStationName(stationId) {
      if (!stationId) return '';
      const station = this.stationList.find(s => s.stationId === stationId);
      return station ? station.stationName : '未知工位';
    },



    // 工位选择变化处理
    onStationChange(index, stationId) {
      const task = this.taskList[index];
      if (stationId) {
        // 根据选中的工位ID找到对应的工位名称
        const selectedStation = this.stationList.find(station => station.stationId === stationId);
        if (selectedStation) {
          this.$set(task, 'stationName', selectedStation.stationName);
        } else {
          console.warn(`未找到工位ID ${stationId} 对应的工位信息`);
        }
      }
      // 自动确认选择
      this.confirmStationSelection(index);
    },

    // 确认工位选择
    confirmStationSelection(index) {
      const task = this.taskList[index];
      if (task.stationId) {
        // 根据选中的工位ID找到对应的工位名称
        const selectedStation = this.stationList.find(station => station.stationId === task.stationId);
        if (selectedStation) {
          this.$set(task, 'stationName', selectedStation.stationName);
        } else {
          console.warn(`未找到工位ID ${task.stationId} 对应的工位信息`);
        }
      }
    },

    getTaskColor(index, opacity = 1) {
      const colors = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'];
      const color = colors[index % colors.length];
      if (opacity !== 1) {
        const r = parseInt(color.slice(1, 3), 16);
        const g = parseInt(color.slice(3, 5), 16);
        const b = parseInt(color.slice(5, 7), 16);
        return `rgba(${r}, ${g}, ${b}, ${opacity})`;
      }
      return color;
    },
    
    // 提交排产
    submitSchedule() {
      // 表单验证
      if (!this.validateForm()) {
        return;
      }
      
      this.loading = true;
      
      // 构建提交数据
      const scheduleData = {
        workOrderId: this.workOrderId,
        tasks: this.taskList.map(task => ({
          workOrderTaskId: task.isNew ? null : task.workOrderTaskId,
          processId: task.processId,
          processName: this.getProcessName(task.processId), // 补充提交 processName
          stationId: task.stationId,
          qtyNum: task.qtyNum, // 修正：后端字段名为 qtyNum
          startTime: task.startTime,
          endTime: task.endTime
        }))
      };
      
      // 确认提示
      this.$confirm('确认提交排产信息?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用后端API
        scheduleWorkOrder(scheduleData).then(response => {
          this.$modal.msgSuccess("排产成功，工单已进入生产队列");
          this.goBack();
        }).catch(() => {
          this.loading = false;
          this.$modal.msgError("排产失败，请检查网络连接或联系管理员");
        });
      }).catch(() => {
        this.loading = false;
        this.$message({
          type: 'info',
          message: '已取消提交'
        });
      });
    },
    
    // 表单验证
    validateForm() {
      if (this.taskList.length === 0) {
        this.$modal.msgError("请至少添加一个工序任务");
        return false;
      }
      
      // 检查是否有标准工艺路线中的必要工序
      const hasRequiredProcesses = [201, 202, 203].every(processId => 
        this.taskList.some(task => task.processId === processId)
      );
      
      if (!hasRequiredProcesses) {
        this.$modal.msgError("标准工艺路线中的必要工序不能缺少");
        return false;
      }
      
      for (let i = 0; i < this.taskList.length; i++) {
        const task = this.taskList[i];
        if (!task.processId) {
          this.$modal.msgError(`第${i + 1}行工序未选择`);
          return false;
        }
        if (!task.stationId) {
          this.$modal.msgError(`第${i + 1}行工位未选择`);
          return false;
        }
        if (!task.qtyNum || task.qtyNum <= 0) {
          this.$modal.msgError(`第${i + 1}行计划数量必须大于0`);
          return false;
        }
        if (!task.startTime) {
          this.$modal.msgError(`第${i + 1}行开始时间未填写`);
          return false;
        }
        if (!task.endTime) {
          this.$modal.msgError(`第${i + 1}行结束时间未填写`);
          return false;
        }
        if (new Date(task.startTime) >= new Date(task.endTime)) {
          this.$modal.msgError(`第${i + 1}行开始时间必须小于结束时间`);
          return false;
        }
      }
      
      return true;
    },

    // 获取可用工位列表
    getAvailableStations(processId) {
      if (!processId) return [];
      return this.stationList.filter(station => station.processId === processId);
    },

    // 获取当天指定小时的时间
    getTodayTime(hour) {
      const d = new Date();
      d.setHours(hour,0,0,0);
      return d.getFullYear() + '-' + String(d.getMonth()+1).padStart(2,'0') + '-' + String(d.getDate()).padStart(2,'0') + ' ' + String(d.getHours()).padStart(2,'0') + ':' + String(d.getMinutes()).padStart(2,'0') + ':' + String(d.getSeconds()).padStart(2,'0');
    }
  }
};
</script>

<style scoped>
.app-container {
  height: calc(100vh - 84px); /* 调整为您实际的导航栏高度 */
  display: flex;
  flex-direction: column;
  overflow: hidden; /* 防止整个容器出现滚动条 */
}

.info-card {
  flex-shrink: 0; /* 不允许卡片缩小 */
  margin-bottom: 15px;
}

.scrollable-content {
  flex: 1; /* 占用剩余空间 */
  overflow-y: auto; /* 只有内容区域出现滚动条 */
  padding-right: 5px; /* 为滚动条留出空间 */
}

.task-card {
  margin-bottom: 15px;
}

.task-table-container {
  margin-bottom: 15px;
}

.gantt-card {
  margin-bottom: 20px;
}

/* 工位显示样式 */
.station-display {
  display: flex;
  align-items: center;
  justify-content: center;
}

.station-select {
  display: flex;
  align-items: center;
  justify-content: center;
}


</style>